import { ITodoItem } from "../interfaces"
import state, {IState} from './state';

interface IAction {
  type: string;
  value: any;
}

// 初始化store
const localState:IState = JSON.parse(localStorage.getItem('state') as string);
const initState: IState = localState ? localState : state;

export default function reducer(state = initState, action: IAction) {
  console.log('exec->reducer  action', action);
  let _state = JSON.parse(JSON.stringify(state));
  if(action.type === 'addTodo') {
    action.value.id = _state.todoList.length + 1;
    _state.todoList.push(action.value);
  }

  if(action.type === 'updateTodo') {
    let list: ITodoItem[] = _state.todoList;
    let len: number = list.length;
    let todoItem: ITodoItem = JSON.parse(JSON.stringify(action.value));
    let todoId:number = 0;
    const id = todoItem.id;
    let index = -1;
    for(let i = 0; i < len; i++) {
      todoId = list[i].id as number;
      if(todoId === id) {
        index = i;
        break;
      }
    }
    
    _state.todoList.splice(index, 1, todoItem);
  }

  if(action.type === 'deleteTodo') {
    let list: ITodoItem[] = _state.todoList;
    let len: number = list.length;
    let todoId:number = 0;
    const id = action.value;
    let index = -1;
    for(let i = 0; i < len; i++) {
      todoId = list[i].id as number;
      if(todoId === id) {
        index = i;
        break;
      }
    }
    
    _state.todoList.splice(index, 1);
  }


  if(action.type === 'checkIsMobile') {
    _state.isMobile = action.value;
  }

  _state.count = _state.todoList.length;

  // store持久化
  localStorage.setItem('state', JSON.stringify(_state));

  return _state;
}